package com.shiguiwu.springmybatis.algorithm.sort;

/**
 * @description: 冒泡排序
 * @author: stone
 * @date: Created by 2021/3/15 22:37
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.algorithm.sort
 */
public class BubbleSort extends AbstractSort implements Sort {
    public BubbleSort(int[] array) {
        super(array);
        this.array = array;
    }

    /**
     * 冒泡排序
     */
    @Override
    public void sort() {
        int length = array.length;
        int temp;
        for (int i = 0; i < length -1; i++) {
            for (int j = 0; j < length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }

    }


    /**
     * 用一个标识还慢些
     */
    public void sort1() {
        int length = array.length;
        int temp = 0;
        boolean flag = false;
        for (int i = 0; i < length -1; i++) {
            for (int j = 0; j < length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    flag = true;
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
            if (!flag) {
                break;
            }
            else {
                flag = false;
            }
        }

    }
}
